<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
  <br/>
</template>

<script>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import useStore from "../store/index.ts";

export default {
  components: { Editor, Toolbar },

  props: {
    patientId: {
      type: Number,
      required: true,
    },
    articleContent: {
      type: String,
      required: true,
    },
  },

  setup(props, { emit }) {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();

    // 内容 HTML
    const valueHtml = ref("<p>hello</p>");

    // 工具栏的配置
    const toolbarConfig = {};

    // 编辑栏的配置
    const editorConfig = {
      placeholder: "请输入内容...",
      MENU_CONF: {}, // 菜单配置对象
    };

    //server: "http://localhost:8080/vaccineResults/file/upload", // 上传图片的接口
    // 配置编辑栏中的图片上传
    editorConfig.MENU_CONF["uploadImage"] = {
      server: import.meta.env.VITE_APP_API_BASE_URL+"/vaccineResults/file/upload", // 上传图片的接口
      fieldName: "file", // 也是后端接口接收的参数名称
    };

    // 初始化编辑器内容
    const initHtml = (html = '') => {
      valueHtml.value = html;
      console.log("初始化编辑器内容");
    };

    // 模拟 ajax 异步获取内容
    onMounted(() => {
      setTimeout(async () => {
        // 获取内容的逻辑可以在这里添加
      }, 1500);
    });

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor) {
        editor.destroy();
      }
    });

    // 处理内容变化
    const handleChange = () => {
      useStore().editorStore.html = valueHtml.value;
      console.log("内容变化:", useStore().editorStore.html);
    };

    // 创建组件时实例化 editor 对象
    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    // 保存编辑内容
    const save = () => {
      useStore().editorStore.html = valueHtml.value;
      emit("saveArticle", editorRef.value.getHtml());
    };

    return {
      editorRef,
      valueHtml,
      mode: "default", // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleChange,
      initHtml,
      save,
    };
  },
};
</script>

<style scoped>


</style>
